// Client data state management store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ClientData, ChatHistory, Tag } from '@/types'
import { createClientData, createTag as createTagFactory, validateClientData } from '@/types'

export const useClientStore = defineStore('client', () => {
  // State
  const currentClient = ref<ClientData | null>(null)
  const clientHistory = ref<ChatHistory[]>([])
  const availableTags = ref<Tag[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const searchQuery = ref('')
  const searchResults = ref<ClientData[]>([])

  // Getters
  const hasCurrentClient = computed(() => !!currentClient.value)
  
  const clientName = computed(() => currentClient.value?.name || '')
  
  const clientAvatar = computed(() => currentClient.value?.avatar || '/default-avatar.png')
  
  const clientTags = computed(() => currentClient.value?.tags || [])
  
  const clientNotes = computed(() => currentClient.value?.notes || '')
  
  const clientContactInfo = computed(() => {
    if (!currentClient.value) return null
    return {
      email: currentClient.value.email,
      phone: currentClient.value.phone,
      company: currentClient.value.company,
      position: currentClient.value.position,
      location: currentClient.value.location
    }
  })
  
  const clientPreferences = computed(() => currentClient.value?.preferences)
  
  const recentHistory = computed(() => {
    return clientHistory.value
      .sort((a, b) => b.date.getTime() - a.date.getTime())
      .slice(0, 10)
  })
  
  const filteredTags = computed(() => {
    if (!searchQuery.value) return availableTags.value
    return availableTags.value.filter(tag =>
      tag.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  })

  // Actions
  const setCurrentClient = (client: ClientData | null) => {
    currentClient.value = client
    if (client) {
      loadClientHistory(client.id)
      error.value = null
    } else {
      clientHistory.value = []
    }
  }

  const updateClient = (updates: Partial<ClientData>) => {
    if (!currentClient.value) return

    const validation = validateClientData({ ...currentClient.value, ...updates })
    if (!validation.isValid) {
      throw new Error(`Invalid client data: ${validation.errors.join(', ')}`)
    }

    currentClient.value = {
      ...currentClient.value,
      ...updates,
      updatedAt: new Date()
    }
  }

  const updateClientField = (field: keyof ClientData, value: any) => {
    if (!currentClient.value) return
    
    updateClient({ [field]: value })
  }

  const addClientTag = (tag: Tag) => {
    if (!currentClient.value) return
    
    const existingTags = currentClient.value.tags
    if (!existingTags.find(t => t.id === tag.id)) {
      updateClient({
        tags: [...existingTags, tag]
      })
    }
  }

  const removeClientTag = (tagId: string) => {
    if (!currentClient.value) return
    
    updateClient({
      tags: currentClient.value.tags.filter(t => t.id !== tagId)
    })
  }

  const updateClientNotes = (notes: string) => {
    updateClient({ notes })
  }

  const updateClientPreferences = (preferences: Partial<ClientData['preferences']>) => {
    if (!currentClient.value) return
    
    updateClient({
      preferences: {
        ...currentClient.value.preferences,
        ...preferences
      }
    })
  }

  const addCustomField = (key: string, value: any) => {
    if (!currentClient.value) return
    
    updateClient({
      customFields: {
        ...currentClient.value.customFields,
        [key]: value
      }
    })
  }

  const removeCustomField = (key: string) => {
    if (!currentClient.value) return
    
    const { [key]: removed, ...rest } = currentClient.value.customFields
    updateClient({ customFields: rest })
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  const setError = (errorMessage: string | null) => {
    error.value = errorMessage
  }

  const clearError = () => {
    error.value = null
  }

  // API Actions
  const loadClient = async (clientId: string) => {
    try {
      setLoading(true)
      clearError()
      
      // TODO: Replace with actual API call
      // const client = await clientService.getClient(clientId)
      // setCurrentClient(client)
      
      // Mock data for now
      console.log(`Loading client ${clientId}...`)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载客户信息失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const saveClient = async () => {
    if (!currentClient.value) return

    try {
      setLoading(true)
      clearError()
      
      // TODO: Replace with actual API call
      // const updatedClient = await clientService.updateClient(currentClient.value)
      // setCurrentClient(updatedClient)
      
      // Mock save
      console.log('Saving client...', currentClient.value)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '保存客户信息失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const createClient = async (clientData: Partial<ClientData>) => {
    try {
      setLoading(true)
      clearError()
      
      const client = createClientData(clientData)
      const validation = validateClientData(client)
      
      if (!validation.isValid) {
        throw new Error(`Invalid client data: ${validation.errors.join(', ')}`)
      }
      
      // TODO: Replace with actual API call
      // const createdClient = await clientService.createClient(client)
      // setCurrentClient(createdClient)
      
      // Mock creation
      setCurrentClient(client)
      
      return client
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '创建客户失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const deleteClient = async (clientId: string) => {
    try {
      setLoading(true)
      clearError()
      
      // TODO: Replace with actual API call
      // await clientService.deleteClient(clientId)
      
      if (currentClient.value?.id === clientId) {
        setCurrentClient(null)
      }
      
      console.log(`Deleting client ${clientId}...`)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '删除客户失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const loadClientHistory = async (clientId: string) => {
    try {
      // TODO: Replace with actual API call
      // const history = await clientService.getClientHistory(clientId)
      // clientHistory.value = history
      
      // Mock data
      clientHistory.value = []
      console.log(`Loading history for client ${clientId}...`)
    } catch (err) {
      console.error('Failed to load client history:', err)
    }
  }

  const searchClients = async (query: string) => {
    try {
      setLoading(true)
      searchQuery.value = query
      
      if (!query.trim()) {
        searchResults.value = []
        return
      }
      
      // TODO: Replace with actual API call
      // const results = await clientService.searchClients(query)
      // searchResults.value = results
      
      // Mock search
      searchResults.value = []
      console.log(`Searching clients with query: ${query}`)
    } catch (err) {
      console.error('Failed to search clients:', err)
      searchResults.value = []
    } finally {
      setLoading(false)
    }
  }

  const clearSearch = () => {
    searchQuery.value = ''
    searchResults.value = []
  }

  // Tag management
  const loadAvailableTags = async () => {
    try {
      // TODO: Replace with actual API call
      // const tags = await tagService.getTags()
      // availableTags.value = tags
      
      // Mock tags
      availableTags.value = [
        createTagFactory({ name: 'VIP客户', color: '#f59e0b' }),
        createTagFactory({ name: '重要客户', color: '#ef4444' }),
        createTagFactory({ name: '新客户', color: '#10b981' }),
        createTagFactory({ name: '老客户', color: '#6b7280' }),
        createTagFactory({ name: '企业客户', color: '#3b82f6' }),
        createTagFactory({ name: '个人客户', color: '#8b5cf6' })
      ]
    } catch (err) {
      console.error('Failed to load tags:', err)
    }
  }

  const createTag = async (tagData: { name: string; color: string }): Promise<Tag> => {
    try {
      const tag = createTagFactory(tagData)
      
      // TODO: Replace with actual API call
      // const createdTag = await tagService.createTag(tag)
      // availableTags.value.push(createdTag)
      
      availableTags.value.push(tag)
      return tag
    } catch (err) {
      console.error('Failed to create tag:', err)
      throw err
    }
  }

  const updateTag = async (tagId: string, updates: Partial<Tag>) => {
    try {
      // TODO: Replace with actual API call
      // const updatedTag = await tagService.updateTag(tagId, updates)
      
      const tagIndex = availableTags.value.findIndex(t => t.id === tagId)
      if (tagIndex >= 0) {
        availableTags.value[tagIndex] = {
          ...availableTags.value[tagIndex],
          ...updates
        }
      }
    } catch (err) {
      console.error('Failed to update tag:', err)
      throw err
    }
  }

  const deleteTag = async (tagId: string) => {
    try {
      // TODO: Replace with actual API call
      // await tagService.deleteTag(tagId)
      
      availableTags.value = availableTags.value.filter(t => t.id !== tagId)
      
      // Remove tag from current client if present
      if (currentClient.value) {
        updateClient({
          tags: currentClient.value.tags.filter(t => t.id !== tagId)
        })
      }
    } catch (err) {
      console.error('Failed to delete tag:', err)
      throw err
    }
  }

  // Initialize store
  const initialize = () => {
    loadAvailableTags()
  }

  return {
    // State
    currentClient,
    clientHistory,
    availableTags,
    loading,
    error,
    searchQuery,
    searchResults,
    
    // Getters
    hasCurrentClient,
    clientName,
    clientAvatar,
    clientTags,
    clientNotes,
    clientContactInfo,
    clientPreferences,
    recentHistory,
    filteredTags,
    
    // Actions
    setCurrentClient,
    updateClient,
    updateClientField,
    addClientTag,
    removeClientTag,
    updateClientNotes,
    updateClientPreferences,
    addCustomField,
    removeCustomField,
    setLoading,
    setError,
    clearError,
    
    // API Actions
    loadClient,
    saveClient,
    createClient,
    deleteClient,
    searchClients,
    clearSearch,
    
    // Tag management
    loadAvailableTags,
    createTag,
    updateTag,
    deleteTag,
    
    // Lifecycle
    initialize
  }
})